﻿using System.Collections.Generic;
using System.Linq;
using mqtttLib.Helper;
using mqtttLib.Messages.Base;

namespace mqtttLib.Messages
{
    /// <summary>
    /// 取消订阅
    /// </summary>
    public sealed class UnsubscribeMessage : MqttMessagePacketId
    {
        public List<string> Topics = new List<string>();
         
        public UnsubscribeMessage()
            : base(MessageType.UNSUBSCRIBE)
        {
        }
         
        public override byte[] GetDataBytes()
        {

            var result = new LinkedList<byte>();
            //variable header
            if (FixedHeader.Qos == Qos.AtLeastOnce || FixedHeader.Qos == Qos.ExactlyOnce)
            {
                PacketIdentifier = GetPacketIdentifier();
                result.AddLast(PacketIdentifier);
            }
            //有效载荷
            foreach (var item in Topics)
            {
                result.AddLast(item);        //主题 
            }
            FixedHeader.RemaingLength = result.Count;
            result.AddFirst(FixedHeader.GetDataBytes());
            return result.ToArray();
        }

        public override void GetDataObject(byte[] buffers)
        {
            int offset = GetStartOffset(buffers);  // int offset = buffers.Length - FixedHeader.RemaingLength;
            //variable header
            if (FixedHeader.Qos == Qos.AtLeastOnce || FixedHeader.Qos == Qos.ExactlyOnce)
                PacketIdentifier = buffers.ReadShort(ref offset);
            if (buffers.Length > 2)
            {
                while (buffers.Length > offset)
                {
                    Topics.Add(buffers.ReadString(ref offset));


                }
            }

        }

        public void Unsubscribe(string topic)
        {
            Topics.Add(topic);
        }


    }
    /// <summary>
    /// 取消订阅回复
    /// </summary>

    public sealed class UnsubscribeAckMessage : MqttMessagePacketId
    {
        public UnsubscribeAckMessage()
            : base(MessageType.UNSUBACK)
        {
        }
         
        public override byte[] GetDataBytes()
        {

            var result = new LinkedList<byte>();
            //variable header
            if (FixedHeader.Qos == Qos.AtLeastOnce || FixedHeader.Qos == Qos.ExactlyOnce)
            {
                PacketIdentifier = GetPacketIdentifier();
                result.AddLast(PacketIdentifier);
            }
            //有效载荷 
            FixedHeader.RemaingLength = result.Count;
            result.AddFirst(FixedHeader.GetDataBytes());
            return result.ToArray();
        }

        public override void GetDataObject(byte[] buffers)
        {
            int offset = GetStartOffset(buffers);  // int offset = buffers.Length - FixedHeader.RemaingLength;
            //variable header
            if (FixedHeader.Qos == Qos.AtLeastOnce || FixedHeader.Qos == Qos.ExactlyOnce)
                PacketIdentifier = buffers.ReadShort(ref offset); 
        }

    }
}
